package com.xujl.rxtask;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.xujl.task.RxExecutor;
import com.xujl.task.RxLog;
import com.xujl.task.dual.DualManager;

import java.util.WeakHashMap;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * <pre>
 *     @author : xujl
 *     e-mail : 597355068@qq.com
 *     time   : 2018/7/19
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks {
    private RefWatcher refWatcher;
    private static final String TAG = "MyApplication";
    private static final WeakHashMap<Activity, String> mWeakHashMap = new WeakHashMap<>();

    @Override
    public void onCreate () {
        super.onCreate();
        Log.e("cpu核心数：", "" + Runtime.getRuntime().availableProcessors());
        RxExecutor.getInstance().init();
        RxExecutor.getInstance().setDebug(true);
        DualManager.getInstance().init(100000);
        refWatcher = setupLeakCanary();
        registerActivityLifecycleCallbacks(this);
    }

    private RefWatcher setupLeakCanary () {
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return RefWatcher.DISABLED;
        }
        return LeakCanary.install(this);
    }

    public static RefWatcher getRefWatcher (Context context) {
        MyApplication leakApplication = (MyApplication) context.getApplicationContext();
        return leakApplication.refWatcher;
    }

    @Override
    public void onActivityCreated (@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        RxLog.d(TAG, "onActivityCreated:" + activity);
        mWeakHashMap.put(activity, activity.getClass().getSimpleName());
    }

    @Override
    public void onActivityStarted (@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed (@NonNull Activity activity) {

    }

    @Override
    public void onActivityPaused (@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped (@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState (@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed (@NonNull Activity activity) {
        RxLog.d(TAG, "onActivityDestroyed:" + activity);
    }

    public static void printActivityStack () {
        RxLog.d(TAG, "activity stack size:" + mWeakHashMap.size());
    }
}
